/** 
 * @memo 明细报表Ext-detailgrid方法 
 * @author lic
 * @sample 粘贴用
 
 		grid = new DetailGrid({ 
	   		id:'grid',
	   		height:all_height-180,
			border:false,
			region: 'center',
			dKey:'id',
			split:true,
			autoLoad:false,
			pageSize:6,
			bodyStyle:'overflow:auto;',
		    trackMouseOver:true,
		    iconCls:'icon-grid',
		    enableHdMenu:false,
		    enableColumnMove: false,
		    enableColumnHide:false,
			frame:true,
			autoScroll:true,
			stripeRows: true,
			loadMask:{msg:'正在加载数据，请稍候...'},
			currentTime:'200912'
	    });
		 
 */
var DetailGrid = Ext.extend(Ext.grid.EditorGridPanel,{
	
  /**
   * 初始化属性
   */
	headFlag:true, //第一加载初始化复杂表头
    customercolumn:'_customer_column_',
	bodyStyle:'padding:0px',
	clicksToEdit:1,
	stripeRows:true,
	trackMouseOver:true,
	iconCls:'icon-grid',
	loadMask:{msg:'正在加载数据，请稍候……'},
	cm:null,
	enableColumnMove:false,
	enableHdMenu:false,
	parseHeader:true, //是否第一次加载,第一次加载会自动创建header和reader
		
	/**
   * 初始化方法
   */
	initComponent : function(){
			 Grid.superclass.initComponent.call(this);
			 this.pageSize=this.pageSize||20;
			 this.baseParams=this.baseParams||{};
			 if(typeof(this.dKey)!=undefined)
				 this.key = this.dKey;
			 this.baseParams.key=this.key;
			 this.tools=this.tools||[];
			 var head=[]; //复杂表头
             var collist; //宾栏
             var columns; //宾栏表头
             var xmlId; //report-id
             var queryConditions; //查询条件
             //同步请求后台获取宾栏json ext3.0没找到支持同步的ajax，暂时用query
 			jQuery.ajax({
					type: "POST",
					url: getRootPath()+'/tableRowQuery.table',
					async:false,
					gridId:this.id,
					data:{
	    	 			Constant_DataSource_:'dataSource',
	       	 			Constant_TableName_:'t_reportdetail',
	       	 			Constant_PK_:this.key,
	       	 			Is_Ajax_:'true' 		
	   	 	     	},
					success: function(obj){
	   	 	     		 obj = replaceAll(obj,'\r\n','');
		   	 	     	 var result = Ext.util.JSON.decode(obj);
		   	 	     	 Ext.getCmp(this.gridId).title="<b><span style='float:left;' id='tab_tit'>"+result.NAME_+"</span></b><span style='float:right;margin-right:20px;'><img id='tab_xls' style='cursor: pointer;margin-left: 20px;' src='"+getRootPath()+"/images/report/icon_excel.gif' alt='导出Excel'/></span>";
		   	 	     	 if((result.HEAD_)!='null')
		   	 	     		 head = Ext.util.JSON.decode(result.HEAD_);
		   	 	     	 columns = result.COL_LIST_HEAD_.split(',');
		   	 	     	 xmlId = result.XML_ID_;
		   	 	     	 queryConditions = result.QUERY_CONDITIONS_;
	   	 	     	 	 collist = result.COL_LIST_JSON_;
	   	 	     	}
			}); 
 			//设置查询参数
 			this.baseParams.collist=collist;
 			this.baseParams.xmlId=xmlId;
 			if(queryConditions == 'null')
 				queryConditions = '';
 			this.baseParams.conditions=queryConditions;
 			this.baseParams.currentTime=this.currentTime;
			 if(!isNull(this.isRemoteExport)){
				 	this.tools.push({
				 		id:'save',
				 		qtip:'导出Excel',
				 		handler: function(e, t, p){
				 			p.exportData(p.isRemoteExport);
				 	}});
			 }
			 this.viewConfig= { 
					 columnsText: '显示列', 
					 sortAscText: '升序', 
					 sortDescText: '降序',
					 forceFit:this.isForceFit	
			 };
			 if(this.isCheck&&isNull(this.singleSelect))
			 {
				 this.singleSelect = false;
			 }
			 if(this.isCheck&&isNull(this.checkOnly))
			 {
				 this.checkOnly = false;
			 }
			 this.selModel=this.isCheck?new Ext.grid.CheckboxSelectionModel({gridId:this.id,singleSelect:this.singleSelect,checkOnly:this.checkOnly}):null;
			 if(!isNull(this.checkId)){ //多选自动保存编号,需要配置checkId
				 this.selModel.on("rowselect",function(o,index,record){ //保存选中行,翻页保存用
					 var grid = Ext.getCmp(o.gridId);
					 var flag = false;
					 for(var i = 0;i<grid.checkedRecord.length;i++){
						 if(grid.checkedRecord[i][grid.checkId] == record.data[grid.checkId]){
							 flag = true;
							 break;
						 }
					 }
					 if(!flag){
						 grid.checkedRecord.push(record.data);
					 }
				 });
				 this.selModel.on("rowdeselect",function(o,index,record){ //删除选中行,翻页保存用
					 var grid = Ext.getCmp(o.gridId);
					 for(var i = 0;i<grid.checkedRecord.length;i++){
						 if(grid.checkedRecord[i][grid.checkId] == record.data[grid.checkId]){
							 grid.checkedRecord.splice(i,1);
							 return;
						 }
					 }
					 
				 });
			 }
			 if(isNull(this.height)){
			 		this.autoHeight=true;
			 }
			 this.isPage = true;
			 //明细报表指定url
			 this.url = '/detailReport.report?method=query';
			 if(!this.url){
				 if(this.isCommonAdapter){
				 	this.baseParams.adapter_id_=this.adapter_id_;
				 	this.url='/customerDetailQueryController.table';
				 }else{
				 	if(typeof(plcdataid)!="undefined"){
				 		this.baseParams.plcdataid=plcdataid;
				 		this.baseParams.plcdatakey=this.key;
				 		this.url='/customerDetailQueryController.table';
				 	}else{
				 		this.url='/adapter2Table.table';
				 	}
				 }}
			 if(this.autoLoad == null)
			 {
				 this.autoLoad = {params:{start:0,limit:this.pageSize}};
			 }
			 var url_ = this.url+(this.url.indexOf("?")>-1?"&decorate=no":"?decorate=no");
			 var storeParam={
				 		id:this.id+'-ds',
						gridId:this.id,
						//url:getRootPath()+url_,
						remoteSort:this.isRemoteSort,
						baseParams:this.baseParams,
						form:this.form,
						autoLoad:this.autoLoad,
						head:'',
					  	reader:new Ext.data.JsonReader({root: 'data', totalProperty: 'totalCount'} ),
					  	sortInfo:((!isNull(this.groupField)) && isNull(this.sortInfo))?{field: this.groupField, direction: "ASC"}:this.sortInfo,
					  	groupField:this.groupField,
					  	proxy: new Ext.data.HttpProxy(new Ext.data.Connection({url:getRootPath()+url_,timeout: 300000000,method:'POST'}))
		     };
			 var ds;
			 if(isNull(this.groupField)){
				 ds=new Ext.data.Store(storeParam);
			 }else{
				 ds=new Ext.data.GroupingStore(storeParam);
				 this.view=new Ext.grid.GroupingView({forceFit:true,groupTextTpl: '{text} ({[values.rs.length]} 条记录)' });
			 }
			 this.store = ds;
			 if(this.isPage){
			 	//var Message='{1} 条记录/页  当前第 {0} 页   共 {2} 条 ';
				var Message='显示 {0} - {1} 条记录,共 {2}条';
				 if(this.showShort==true){
			 		Message='';
			 	}
			 	 this.bbar=new Ext.PagingToolbar({
			 		 	height:30, 
					 	afterPageText: '/ {0}',
					 	beforePageText: '页',
					 	firstText: '第一页',
					 	prevText: '前一页',
					 	nextText: '后一页',
					 	lastText: '最后一页',
					 	refreshText: '刷新',
					 	store: this.store, 
					 	pageSize: this.pageSize,
					 	displayInfo: true, 
					 	displayMsg: Message, 
					 	emptyMsg: "没有数据" 
				 });
				 if(this.bbar){
		            this.elements += ',bbar';
		            if(typeof this.bbar == 'object'){
		                this.bottomToolbar = this.bbar;
		            }
		            delete this.bbar;
	          }
	       }
			 this.ds = ds;
			 ds.on("beforeload",function(o,options){
				 if(!isNull(this.form)){
					 var params=this.form.getForm().getValues();
					 function eachItem(item,index,length) {
						 if (item.isXType("xlovcombo")) {
							 if(item.getValue() != null && item.getValue().trim()!="''"){
								 params[item.id] = item.getValue();
							 }else{
								 params[item.id] = null;
							 }
						 }
					 }   
					 this.form.items.each(eachItem); 
					 Ext.apply(this.baseParams,params);
					 Ext.apply(options.params,params);
				 }
			 });
			 //可多选时能自动选中，为了翻页
			 if(!isNull(this.checkId)){ //多选自动保存编号,需要配置checkId
				 this.store.on('load',function(store, records, options){
					 var grid = Ext.getCmp(store.gridId);
					 var index = [];
					 for(var i = 0;i<records.length;i++){
						 for(var j = 0;j<grid.checkedRecord.length;j++){
							 if(records[i].data[grid.checkId] == grid.checkedRecord[j][grid.checkId]){
								 index.push(i);
								 break;
							 }
						 }
					 }
					 grid.getSelectionModel().selectRows(index,true);
				 });
			 }
			 ds.on("preload",function(a,b){Ext.getCmp(this.gridId).reconfig(a,b,this.gridId)});
			 if(this.isLock){
				 this.colModel=new Ext.ux.grid.LockingColumnModel([{}]);
				 this.view=new Ext.ux.grid.LockingGridView();
			 }else{
				 this.colModel=new Ext.grid.ColumnModel([{}]);
			 }
			 this.colModel.defaultSortable = (this.isRemoteSort!=null||false);
			 //this.selModel=new Ext.grid.RowSelectionModel();
			 if(this.selColumn)
			 {//判断是否有自定义列功能，设为true时页面需要引入webContent/ext3.1/js/gridAdvanced.js
				 this.tools.push({
					    id:'gear',
					    qtip:'自定义列',
					    handler: function(e, target, grid)
					    {
					 			
							 	if(Ext.getCmp('selColumn_win_'+grid.id) == undefined)
								{
									selColumn(grid.key,grid.id,grid.adapter_id_);
								}
							 	var root = Ext.getCmp('selColumn_tree_panel_'+grid.id).root;
							 	root.expand();
								if(!root.firstChild)
								{
									root.appendChild(grid.getTree());
								}
								Ext.getCmp('selColumn_win_'+grid.id).show();
						}
					});
			 }
			 if(this.selQuery)
			 {//判断是否有自定义查询功能，设为true时页面需要引入webContent/ext3.1/js/gridAdvanced.js
				 this.tools.push({
						 id:'pin',
						 qtip:'高级查询',
						 handler: function(e, target, grid)
						 {
						 	if(Ext.getCmp('selQuery_win_'+grid.id) == undefined)
						 	{
						 		selQuery(grid.key,grid.id,grid.adapter_id_);
						 		Ext.getCmp('selQuery_tree_panel_'+grid.id).root.expand();
					 			Ext.getCmp('selQuery_tree_panel_'+grid.id).root.appendChild(grid.getTree());
						 	}
				 			Ext.getCmp('selQuery_win_'+grid.id).show();
			 				Ext.getCmp('gridSelQuery_'+grid.id).load();
				 		}
				 });
			 }
			 this.checkedRecord=this.checkedRecord||[];
			 //添加表头编辑
			 this.addListener('headercontextmenu', rightClickFn);
			 this.addListener('headerdblclick', headerDbclickFn);
			 this.addListener('headerclick', headerClickFn);
			 //添加行数锁定
             this.bottomToolbar.insert(11,{
     			xtype: 'label',
     			height: 10,
     			width:100,
     			html:'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;显示行数：'
     		});
             this.bottomToolbar.insert(12,{
     			id:'rowCount1'+this.id,
         		xtype: 'numberfield',
         		allowDecimals:false, 
         		height: 10,
         		width:100
     		});
             this.bottomToolbar.insert(13,{
     			xtype: 'label',
     			height: 10,
     			width:10
     		});
             this.bottomToolbar.insert(14,{
         		xtype: 'button',
         		height: 10,
         		text:'检&nbsp;&nbsp;索',
         		gridId:this.id,
         		handler: function (combo,record,index){
     					var rows = Ext.getCmp('rowCount1'+this.gridId).getValue();
     					if(rows==""||rows==null)
     						alert("没有输入控制行数");
     					else
     					{
     						Ext.getCmp(this.gridId).baseParams.rows = rows;
     						Ext.getCmp(this.gridId).baseParams.method = "rows";
     						Ext.getCmp(this.gridId).load();
     					}
               }
     		});
 			//复杂表头配置
 			this.plugins = [new Ext.ux.plugins.GroupHeaderGrid({rows:[],columns:[]})];
 			//设置回调
 			this.callback = function(cm) {
					for(var i=0;i<this.ds.head.length;i++)
					{
						this.ds.head[i].header=columns[i];
					}
					if(this.headFlag)
					{
						this.reconfigure(this.ds, new Ext.grid.ColumnModel({defaults:{align:'center'},rows:head,columns:this.ds.head}));
					}
					else
					{
						this.reconfigure(this.ds, new Ext.grid.ColumnModel({defaults:{align:'center'},rows:this.getColumnModel().rows,columns:this.ds.head}));
					}
			}
	},

  /**
   * 方法
   */	
	setKey:function(key){
		this.ds.baseParams.key = key;
		this.parseHeader = true; //需要重新配置header
	},
	getKey:function(){
		return this.ds.baseParams.key;
	},
	setCallBack:function(callback){
		this.ds.callback = callback;
		this.parseHeader = true; //需要重新配置header
	},
	load:function(){
		this.ds.load({params:{start:0,limit:this.pageSize}});
	},
	reload:function(){
		this.store.load();
	},
	getParam:function(p){
		return this.ds.baseParams[p];
	},
	setParam:function(p,v){
		this.ds.baseParams[p]=v;
	},
	setParams:function(j){
		for(var p in j){
			this.setParam(p,j[p]);
		}
	},
	getHead:function(){
		return this.ds.head;
	},
	exportData:function(flag){
		if(flag){
			var url = getRootPath()+"/extExportExcel.report?decorate=no&key="+this.ds.baseParams.key+"&filename="+encodeURI(this.title);
			for(var p in this.ds.baseParams){
				url+="&"+p+"="+this.ds.baseParams[p];
			}
			url+="&isExcelRank="+this.isExcelRank;
			if(this.isCommonAdapter)
			{
				var start = 0,limit = this.ds.getTotalCount();
				url += "&adapter_id_="+this.adapter_id_+"&start="+start+"&limit="+limit;
			}
			window.location.href=url;
		}
		else{
			exportData(this.id,this.title);
		}
	},
	getTree:function(){
		var j1 = this.ds.head;
		var j2 = "[{}";
		for(var p=0;p<j1.length;p++)
		{
			if(j1[p].dataIndex.indexOf(this.customercolumn)==-1)
				j2+=",{'text':'"+j1[p].header+"',expanded: false,leaf:true}";
		};
		j2+="]";
		j2=eval(j2.replace("{},",""));
		return j2;
	},
	getSelectionsByCheckId:function(){
		var result='';
		for(var i=0;i<this.checkedRecord.length;i++){
			result += "'"+this.checkedRecord[i][this.checkId]+"'";
			if(i+1<this.checkedRecord.length)
				result += ',';
		}
		return result;
	},
	getSelections:function(target){
		var rows = this.getSelectionModel().getSelections();
		if(rows=='')return null;
		var result='';
		for(var i=0;i<rows.length;i++){
			result += rows[i].get(target);
			if(i+1<rows.length)
				result += ',';
		}
		return result;
	},
	reconfig:function(o,j){
		var s = this;
		var data;
		var sort=null;
		var edit=null;
		var lock=null;
		var j_;
		var flag = true; //是否回调的标志
		var reader=[];
		var head=[];
		try{
			data = eval("("+j+")");
			j_ = data.data[0];
		}catch(e){
		}
		if(data && data.norecord){
			//没数据
			flag = false;
		}else if(data && data.error){
			//错误信息
			flag = false;
			show_error_message_win(data.error);
		}
		//解析header
		if(s.parseHeader || flag == false){
			if(s.isRemoteSort!=null && flag)
				sort = true;
			if(s.isRank && flag)
				head.push(new Ext.grid.RowNumberer());
			if(s.isCheck && flag)
				head.push(new Ext.grid.CheckboxSelectionModel());
			edit = s.isEdit==true?(new Ext.form.TextField({allowBlank: true})):null;
			for(var p in j_){
				if(p && trim(p) != '' && p != 'ordertype' && p != 'recordnum'){
					if(s.lockedField && s.lockedField.indexOf(p) != -1)
						lock=true;
					head.push({header:p.replace(s.customercolumn,''),dataIndex:p,locked:lock,sortable:sort,editor:edit});
				}
			}
			s.ds.head = head;
			s.getColumnModel().setConfig(head);
			var cm=s.getColumnModel();
			cm.setEditor=function(i,c){
				cm.config[i].editor.destroy();
				cm.config[i].editor = new Ext.grid.GridEditor(c);
			};	
			if(flag && s.callback)s.callback(cm);
			if(flag&&s.events.callback_)
				(s.fireEvent("callback_",cm));
			s.parseHeader = false;
		}
		//解析reader
		for(var p in j_){
			if(p && trim(p) != '' && p != 'ordertype' && p != 'recordnum'){
				reader.push({name:p});
			}
		}
		o.reader = new Ext.data.JsonReader({root: 'data', totalProperty: 'totalCount'},reader );
		o.recordType = o.reader.recordType;
		s.ds.fields = o.recordType.prototype.fields;
		if(!flag)s.parseHeader = true;
		
	}
});

Ext.reg('xgrid', Grid);
//非空判断
function isNull(o){
	return (typeof(o) == 'undefined' || o == null);
}